package io.tij;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class BufferToText {
	
	private static final int BSIZE = 1024;
	
	public static void main(String[] args) throws Exception{
		String filePath = "data2.txt";
		FileChannel fc = new FileOutputStream(filePath).getChannel();
		fc.write(ByteBuffer.wrap("Some text".getBytes()));
		fc.close();
		fc = new FileInputStream(filePath).getChannel();
		ByteBuffer buff = ByteBuffer.allocate(BSIZE);
		fc.read(buff);
		buff.flip();
		// Dosen't work
		System.out.println("Default: " + buff.asCharBuffer());
		
		// Decode use system's default Charset:
		buff.rewind();
		String encoding = System.getProperty("file.encoding");
		System.out.println("System's defalut Charset: " + encoding);
		Charset charset = Charset.forName(encoding);
		System.out.println("Decoding with System's default Charset: " + charset.decode(buff));
		
		// Write with UTF-16
		fc = new FileOutputStream(filePath).getChannel();
		fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE")));
		fc.close();
		buff.clear();
		fc = new FileInputStream(filePath).getChannel();
		fc.read(buff);
		buff.flip();
		System.out.println("Read UTF-16 File: " + buff.asCharBuffer());
		
		// Write and Read with CharBuffer
		buff = ByteBuffer.allocate(26);
		buff.asCharBuffer().put("Other text");
		fc = new FileOutputStream(filePath).getChannel();
		fc.write(buff);
		fc.close();
		fc = new FileInputStream(filePath).getChannel();
		buff.clear();
		fc.read(buff);
		buff.flip();
		System.out.println("Write and read with CharBuffer: " + buff.asCharBuffer());
	}

}
